/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.netconsole.dao;

import java.util.ArrayList;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.netconsole.model.Equipment;

/**
 *
 * @author aurel
 */
public class EquipmentDAOImpl implements EquipmentDAO{
        private SessionFactory sf;

    public EquipmentDAOImpl(SessionFactory sf) {
            this.sf = sf;
    }

    @Override
    public Equipment getEquipmentByID(String id){
        Session session = sf.openSession();
        Transaction tx = session.beginTransaction();
        Query query = session.createQuery("from Equipment where id=:id");
        query.setString("id", id);
        Equipment equipment = (Equipment) query.uniqueResult();
        if(equipment != null){
                System.out.println("User Retrieved from DB::"+equipment);
        }
        tx.commit();session.close();
        return equipment;
    }

    @Override
    public Equipment insertEq(Equipment equipment){

        try{
            Session session = sf.openSession();
            session.beginTransaction();
            session.save(equipment);
            session.getTransaction().commit();
        } catch (Exception e){

        }

        return equipment;
    }

    @Override
    public List<Equipment> listEquipment(){
        List<Equipment> lst = new ArrayList<>();
        Session session = sf.openSession();
        lst = session.createQuery("from Equipment").list();
        return lst;
    }

    @Override
    public Equipment modifEq(Equipment equipment) {
         try{
            Session session = sf.openSession();
            session.beginTransaction();
            Equipment eq = getEquipmentByID(Integer.toString(equipment.getId()));
            if (eq != null){
                eq.setIp(equipment.getIp());
                eq.setDns(equipment.getDns());
                eq.setDescription(equipment.getDescription());
                eq.setType(equipment.getType());
                session.update(eq);              
            }
            session.getTransaction().commit();
        } catch (Exception e){

        }

        return equipment;
    }
}
